<?php
require_once __DIR__ . '/Autoloader.php';

use Workerman\Worker;

$worker = new Worker('websocket://192.168.248.128:8000'); // 创建一个WebSocket服务器，监听在本地的8000端口

$worker->count = 1; // 设置服务器进程数为1，即单进程模式

// 存储每个连接的用户ID和连接对象的映射关系
$connections = [];

$worker->onConnect = function ($connection) use (&$connections) {
    echo "New connection\n"; // 当有新的连接建立时，打印出提示信息
    
    $connection->onWebSocketConnect = function ($connection, $http_header) use (&$connections) {
        // 从请求头中获取用户ID
        $userId = $_GET['user_id'];
        
        // 将用户ID和连接对象进行映射存储
        $connections[$userId] = $connection;
    };
};

$worker->onMessage = function ($connection, $data) use (&$connections) {
    $message = json_decode($data, true); // 解析收到的消息
    
    $receiverId = $message['receiver_id']; // 获取接收者ID
    $content = $message['content']; // 获取消息内容
    
    if (isset($connections[$receiverId])) {
        $receiverConnection = $connections[$receiverId];
        $receiverConnection->send($content); // 将消息发送给接收者连接的客户端
    }
};

$worker->onClose = function ($connection) use (&$connections) {
    echo "Connection closed\n"; // 当连接关闭时，打印出提示信息
    
    // 当连接关闭时，移除对应的用户ID和连接对象的映射关系
    foreach ($connections as $userId => $conn) {
        if ($conn === $connection) {
            unset($connections[$userId]);
            break;
        }
    }
};

Worker::runAll(); // 运行服务器
?>